package com.ygqh.baby.controller.mobile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.*;
import com.ygqh.baby.constant.Constant;
import com.ygqh.baby.exception.YgException;
import com.ygqh.baby.model.BargainProductListModel;
import com.ygqh.baby.model.CommitKjOrderParam;
import com.ygqh.baby.model.ProductBargainData;
import com.ygqh.baby.model.YgPtSkuInfo;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.po.YgUserBargain;
import com.ygqh.baby.po.YgUserBargainDetail;
import com.ygqh.baby.service.*;
import com.ygqh.baby.service.impl.DocumentConstant;
import com.ygqh.baby.utils.SessionUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller()
@RequestMapping("/mobile/bargain")
public class YgBargainController extends BaseController {
    protected Logger logger = Logger.getLogger(this.getClass());
    @Autowired
    private YgUserBargainService ygUserBargainService;
    @Autowired
    private YgBargainService ygBargainService;
    @Autowired
    private YgUserBargainDetailService ygUserBargainDetailService;
    @Autowired
    private YgShoppingCarService ygShoppingCarService;
    @Autowired
    private YgUserService ygUserService;

    @Autowired
    private YgOrderLogService ygOrderLogService;

    @Autowired
    private DocumentConstant documentConstant;


    @RequestMapping(value = "/addUserBargain")
    @ResponseBody
    public JSONPObject addUserBargain(Long productId, Long skuId, Long userAddressId, String callback) {
        YgUser user = SessionUtil.getCurrentUser();
        Message message = ygUserBargainService.
                addUserBargain(productId, userAddressId, user.getId(), Constant.YIIGOO_PLATFORM_NO, skuId);
        return new JSONPObject(callback, message);

    }

    @RequestMapping(value = "/findProductBargainData")
    @ResponseBody
    public JSONPObject findProductBargainData(Long productId, Long bargainId, String callback) {
        ProductBargainData productBargainData = ygBargainService.findProductBargainData(productId, bargainId, Constant.YIIGOO_PLATFORM_NO);
        return new JSONPObject(callback, Message.success(productBargainData));

    }

    @RequestMapping(value = "/findBargainProductList")
    @ResponseBody
    public JSONPObject findBargainProductList(QueryInfo queryInfo, Long bargainId, String callback) {
        List<BargainProductListModel> bargainProductList =
                ygBargainService.findBargainProductList(queryInfo, bargainId, SalesPlatform.Yiigoo);
        return new JSONPObject(callback, Message.success(bargainProductList));
    }

    @RequestMapping("/findUserBargainList")
    @ResponseBody
    public JSONPObject findUserBargainList(QueryInfo queryInfo, Long productId, Long bargainId, String callback) {
        YgUser user = SessionUtil.getCurrentUser();
        List<YgUserBargain> list = ygUserBargainService.findUserBargainList(queryInfo, productId, bargainId,
                user.getId(), Constant.YIIGOO_PLATFORM_NO);
        return new JSONPObject(callback, Message.success(list));

    }

    @RequestMapping("/findCutList")
    @ResponseBody
    public JSONPObject findCutList(Long userBargainId, String callback) {
        List<YgUserBargainDetail> list = ygUserBargainDetailService.findCutList(userBargainId);
        return new JSONPObject(callback, Message.success(list));

    }

    @RequestMapping("/findUserBargainInfo")
    @ResponseBody
    public JSONPObject findUserBargainInfo(Long userBargainId, Long productId, Long userId, String callback) {
        Map<String, Object> result = new HashMap<>();
        Boolean existed = false;
        Object data = null;
        if (userBargainId != null) {
            // 分享页，剁手清单页
            data = ygUserBargainService.findUserBargainInfo(userBargainId);
        } else {
            // 专题页进去
            ProductBargainData productBargainData = ygBargainService.findProductBargainData(productId, null, Constant.YIJIADIAN_PLATFORM_NO);
            if (productBargainData == null || !PromotionStatus.Running.equals(productBargainData.getPromotionStatus())) {
                return new JSONPObject(callback, Message.error("亲，您来晚了，活动已结束。", null));
            }
            YgUserBargain userBargain = ygUserBargainService.findUserBargain(userId, productId, productBargainData.getBargainId());
            if (userBargain != null) {
                existed = true;
                data = ygUserBargainService.findUserBargainInfo(userBargain.getId());
            } else {
                data = productBargainData;
            }
        }
        result.put("existed", existed);
        result.put("data", data);

        return new JSONPObject(callback, Message.success(result));
    }

    @RequestMapping("/cutPrice")
    @ResponseBody
    public JSONPObject cutPrice(String userName, String openId, String headUrl, String nickName, Long userBargainId,
                                String callback) {
        logger.info("userName=" + userName + ";openId=" + openId + "headUrl=" + headUrl + ";nickName=" + nickName
                + ";userBargainId=" + userBargainId);
        if (StringUtil.isNotBlank(userName)) {
            YgUser user = ygUserService.findByUserName(userName);
            openId = user.getUserName();
            headUrl = user.getHeadImageUrl();
            nickName = user.getNickName();
        } else {
            YgUser user = ygUserService.findByOpenId(openId);
            if (user != null) {
                openId = user.getUserName();
                headUrl = user.getHeadImageUrl();
                nickName = user.getNickName();
            }
        }
        Message message = ygUserBargainService.cutPrice(null, openId, headUrl, nickName, userBargainId);
        if (message.getType().equals(Message.Type.success)) {
            YgUserBargain userBargain = ygUserBargainService.findById(userBargainId);
            YgUserBargainDetail d = (YgUserBargainDetail) message.getExtra();
            YgUser user = ygUserService.findById(userBargain.getUserId());
            if (StringUtil.isNotBlank(user.getOpenId()) && !user.getUserName().equals(openId)) {
                ygUserBargainService.sendCutMsg(nickName, d.getCutPrice(), user.getOpenId(), userBargainId);
            }

        }
        return new JSONPObject(callback, message);
    }

    @RequestMapping("/cutPriceNeedLogin")
    @ResponseBody
    public JSONPObject cutPriceNeedLogin(Long userBargainId, boolean small, String callback) {

        YgUser currentUser = SessionUtil.getCurrentUser();
        String openId = currentUser.getOpenId();
        if (small) {
            openId = currentUser.getSmallOpenId();
        }
        Message message = ygUserBargainService.cutPrice(currentUser.getId(), openId, currentUser.getHeadImageUrl(),
                currentUser.getNickName(), userBargainId);
        if (message.getType().equals(Message.Type.success)) {
            YgUserBargain userBargain = ygUserBargainService.findById(userBargainId);
            YgUserBargainDetail d = (YgUserBargainDetail) message.getExtra();
            YgUser user = ygUserService.findById(userBargain.getUserId());
            if (!userBargain.getUserId().equals(currentUser.getId())) {
                //别人帮砍时发消息
                ygUserBargainService.sendCutMsg(currentUser.getNickName(), d.getCutPrice(), user.getOpenId(), userBargainId, Constant.YIIGOO_PLATFORM_NO);
            }
        }
        return new JSONPObject(callback, message);
    }

    @RequestMapping(value = "findItemInfo")
    @ResponseBody
    public JSONPObject findItemInfo(String skuInfos, Long userBargainId, String callback) throws YgException {

        YgUser user = SessionUtil.getCurrentUser();
        List<YgPtSkuInfo> skuList = JSON.parseObject(skuInfos, new TypeReference<List<YgPtSkuInfo>>() {
        });
        Map<String, Object> itemInfo = ygUserBargainService.findItemInfo(skuList, user.getId(), userBargainId);
        return new JSONPObject(callback, Message.success(documentConstant.MESSAGE_SUCCESS, itemInfo));
    }

    @RequestMapping(value = "commitOrderKJ")
    @ResponseBody
    public ResponseEntity commitOrderPt(CommitKjOrderParam commitKjOrderParam) throws YgException {

        commitKjOrderParam.setPlatformNo(Constant.YIIGOO_PLATFORM_NO);
        YgUser user = SessionUtil.getCurrentUser();
        commitKjOrderParam.setUserId(user.getId());
        ygOrderLogService.addOrderLog(user.getId(), OrderStatus.WaitingPay, user.getUserName(), "提交订单,【入参】：" + JSON.toJSONString(commitKjOrderParam));
        // 保存订单
        Message msg = ygUserBargainService.commitOrderKJ(commitKjOrderParam);
        // 订单保存成功
        if (msg.getType().equals(Message.Type.success)) {
            Map<String, Object> map = (Map<String, Object>) msg.getExtra();
            map.put("openid", user.getOpenId());
            map.put("totalPrice", commitKjOrderParam.getTotalPrice().subtract(commitKjOrderParam.getAccountPrice()));
            msg.setExtra(map);
            msg.setContent("订单提交成功");
            ygOrderLogService.addOrderLog((Long) map.get("orderId"), OrderStatus.WaitingPay, user.getUserName(), "订单提交成功：" + map.toString());
        } else {
            logger.error(
                    "订单提交失败，msgType:" + msg.getType() + ";msg:" + msg.getContent() + ";msgExtra:" + (msg.getExtra() == null ? "" : msg.getExtra().toString()));
        }

        return ResponseEntity.success(msg);
    }
}
